package com.cgah

class UserController {

    def index = {
        redirect(action: "create", params: params)
    }

    def create = {
        // TODO:  write the code!
        def userInstance = new User()
        userInstance.properties = params
        userInstance.enabled = true;

        return [userInstance: userInstance]
    }

    def save = {
        def userInstance = new User(params)
        def userRole = Role.findByAuthority('ROLE_USER') ?: new Role(authority: 'ROLE_USER').save(failOnError: true)
        if (userInstance.save(flush: true)) {
            flash.message = "${message(code: 'default.created.message', args: [message(code: 'user.label', default: 'User'), userInstance.id])}"
            redirect(action: "show", id: userInstance.id)
            if (!userInstance.getAuthorities().contains(userRole)) {
                UserRole.create(userInstance, userRole)
            }
        }
        else {
            render(view: "create", model: [userInstance: userInstance])
        }
    }

       def show = {
        def userInstance = User.get(params.id)
        if (!userInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'user.label', default: 'User'), params.id])}"
            redirect(action: "list")
        }
        else {
            [userInstance: userInstance]
        }
    }
}
